package register;

import config.ConfigLoader;
import config.RPC;
import lombok.extern.log4j.Log4j;
import org.reflections.Reflections;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@Log4j
public class ServiceRegistryOld {
    private static final String CLASS_PATH = "service.";
    // 存放远程对象的缓存
    public static final Map<String, Object> REMOTE_OBJECTS = new HashMap<>();
    public static void scanAndRegisterServices(String host, int port) {
        Reflections reflections = new Reflections(CLASS_PATH);
        Set<Class<?>> serviceClasses = reflections.getTypesAnnotatedWith(RPC.class);

        for (Class<?> serviceClass : serviceClasses) {
            try {
                Object serviceInstance = serviceClass.newInstance();
                // 获取并注册所有接口
                Class<?>[] interfaces = serviceClass.getInterfaces();
                for (Class<?> interf : interfaces) {
                    String interfaceName = interf.getName();
                    registerServiceWithRegistry(host, port, interfaceName, serviceInstance);
                }
            } catch (InstantiationException | IllegalAccessException e) {
                log.error("服务注册失败: " + e.getMessage());
            }
        }
    }
    public static void registerServiceWithRegistry(String host, int port, String serviceName, Object serviceInstance) {
        try (Socket socket = new Socket(host, port);
             ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
             ObjectInputStream input = new ObjectInputStream(socket.getInputStream())) {
            output.writeUTF(serviceName);
            output.writeUTF("register");
            output.writeUTF(ConfigLoader.getServerHost()+":"+ConfigLoader.getServerPort()); // 本服务器的地址
            output.flush();
            String response=input.readUTF();
            log.debug("注册中心响应结果:"+response);
            REMOTE_OBJECTS.put(serviceName, serviceInstance);
        } catch (IOException e) {
            log.error("服务注册失败: " + e.getMessage());
        }
    }
}
